#!/bin/bash

programName=`basename $0`

function help() {
   echo "Syntax: ${programName} [-p port] [-h hostName] [-s] ip"
   exit 1
}

port=80
ip=127.0.0.1
host=""
ssl=0

ARGS=`getopt -o h:p:s --long help -n "${programName}" -- "$@"`
if [ $? != 0 ];
then 
   echo "Terminating..." >&2;
   exit 1;
fi

eval set -- "$ARGS"

while true;
do
   case "$1" in
      -h) host=$2;
          shift 2
          ;;
      -p) port=$2
          shift 2
          ;;
      --help) help
          ;;
      -s) ssl=1
          shift
          ;;
      --) shift;
          break
          ;;
      *) echo "Internal error!";
         exit 1
         ;;
   esac
done

if [ ! $# -eq 1 ];
then
   help
fi

ip=$1
                                                                                                               
fileName=Web_${ip}.log

command="nc ${ip} ${port}"
if [ ${ssl} -eq 1 ];
then
  command="openssl s_client -connect ${ip}:${port} -quiet -crlf"
fi

if [ "_${host}" == "_" ];
then
   echo ${command} >> ${fileName}
   echo GET / HTTP/1.0 >> ${fileName}
   echo >> ${fileName}
   ${command} <<EOF >> ${fileName}
GET / HTTP/1.0

EOF
else
   echo ${command} >> ${fileName}
   echo GET / HTTP/1.1 >> ${fileName}
   echo Host: ${host} >> ${fileName}
   echo >> ${fileName}
   ${command} <<EOF >> ${fileName}
GET / HTTP/1.1
Host: ${host}

EOF
fi

echo >> ${fileName}
echo '--------------------------------------------------------------' >> ${fileName}

for method in OPTIONS TRACE TRACK CONNECT;
do
   echo ${command} >> ${fileName}
   echo ${method} / HTTP/1.0 >> ${fileName}
   echo >> ${fileName}
   ${command} <<EOF >> ${fileName}
${method} / HTTP/1.0

EOF
   echo >> ${fileName}
   echo '--------------------------------------------------------------' >> ${fileName}
done

